package vote.ai.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import vote.ai.domain.entity.CorrectionDict;
import vote.ai.domain.enums.CorrectionModel;
import vote.ai.factory.AiServiceFactory;
import vote.ai.factory.CorrectionFactory;
import vote.ai.mapper.CorrectionDictMapper;
import vote.ai.service.CorrectionDictService;

import java.util.List;

/**
 * Description:纠错字典服务类
 * Author:han
 * Date: 2024-05-21
 */
@Service
public class CorrectionDictServiceImpl extends ServiceImpl<CorrectionDictMapper, CorrectionDict> implements CorrectionDictService {
    @Resource
    private AiServiceFactory aiServiceFactory;

    /**
     * 敏感词替换占位符
     *
     * @param word       源文本
     * @param hasRestore 是否还原
     * @return 替换后文本
     */
    @Override
    public String sensitiveWordPlace(String word, boolean hasRestore) {
        LambdaQueryWrapper<CorrectionDict> queryWrapper = new LambdaQueryWrapper<>();
        //找有占位符的
        queryWrapper.isNotNull(CorrectionDict::getPlaceholder);
        //是敏感词的
        queryWrapper.eq(CorrectionDict::isHasSensitiveWord, true);
        List<CorrectionDict> dicts = this.list(queryWrapper);
        for (CorrectionDict dict : dicts) {
            if (StringUtils.hasText(dict.getPlaceholder())) {
                if (!hasRestore) {
                    word = word.replace(dict.getErrorWord(), dict.getPlaceholder());
                } else {
                    String placeWordStr = String.format("<error-text :%s>%s</error-text>", dict.getErrorWord(), dict.getCorrectWord());
                    word = word.replace(dict.getPlaceholder(), placeWordStr);
                }
            }
        }
        return word;
    }

    /**
     * 本地词库替换 todo 改为向量数据库ai直接根据向量数据库的词以及提示词进行替换就不需要做本地词的先匹配
     *
     * @param text
     * @return
     */
    @Override
    public String localWordReplace(String text) {
        if (!StringUtils.hasText(text)) {
            return text;
        }
        //查看本地词典配置是否开启
        if (!aiServiceFactory.getEnabledServices().containsKey(CorrectionModel.LOCAL)) {
            return text;
        }
        LambdaQueryWrapper<CorrectionDict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CorrectionDict::isHasSensitiveWord, false);
        List<CorrectionDict> dicts = this.list(wrapper);
        for (CorrectionDict dict : dicts) {
            if (!StringUtils.hasText(dict.getCorrectWord()) || !StringUtils.hasText(dict.getErrorWord())) {
                continue;
            }
            //替换 为什么要这样替换
            String replaceStr = String.format("<error-text :%s>%s</error-text>", dict.getErrorWord(), dict.getCorrectWord());
            text = text.replace(dict.getErrorWord(), replaceStr);
        }
        return text;
    }
}
